---
- name: Install firewalld packages
  yum:
    name: firewalld
    state: present
  register: install_result

- name: Check if iptables-services is installed
  command: rpm -q iptables-services
  register: pkg_check
  failed_when: pkg_check.rc > 1
  changed_when: no

- name: Ensure iptables services are not enabled
  service:
    name: "{{ item }}"
    state: stopped
    enabled: no
  with_items:
  - iptables
  - ip6tables
  when: pkg_check.rc == 0

- name: Reload systemd units
  command: systemctl daemon-reload
  when: install_result | changed

- name: Start and enable firewalld service
  service:
    name: firewalld
    state: started
    enabled: yes
  register: result

- name: need to pause here, otherwise the firewalld service starting can sometimes cause ssh to fail
  pause: seconds=10
  when: result | changed

- name: Mask iptables services
  command: systemctl mask "{{ item }}"
  register: result
  changed_when: "'iptables' in result.stdout"
  with_items:
  - iptables
  - ip6tables
  when: pkg_check.rc == 0
  ignore_errors: yes

# TODO: Ansible 1.9 will eliminate the need for separate firewalld tasks for
# enabling rules and making them permanent with the immediate flag
- name: Add firewalld allow rules
  firewalld:
    port: "{{ item.port }}"
    permanent: false
    state: enabled
  with_items: os_firewall_allow
  when: os_firewall_allow is defined

- name: Persist firewalld allow rules
  firewalld:
    port: "{{ item.port }}"
    permanent: true
    state: enabled
  with_items: os_firewall_allow
  when: os_firewall_allow is defined

- name: Remove firewalld allow rules
  firewalld:
    port: "{{ item.port }}"
    permanent: false
    state: disabled
  with_items: os_firewall_deny
  when: os_firewall_deny is defined

- name: Persist removal of firewalld allow rules
  firewalld:
    port: "{{ item.port }}"
    permanent: true
    state: disabled
  with_items: os_firewall_deny
  when: os_firewall_deny is defined
